
<!DOCTYPE html>
<html lang="zh" class="h-100">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>学员签到检查程序</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.4.1/dist/css/bootstrap.min.css" />
    <style>
        body {
            height: 100%;
            background-color: #fafafa;
        }

        main {
            padding: 20px 0;
        }

        label {
            font-size: 18px;
            font-weight: bold;
        }

        textarea {
            font-weight: bold !important;
        }

        input::placeholder,
        textarea::placeholder {
            color: #aaa !important;
        }

        .form-control[readonly] {
            transition: all .13s linear;
        }

        .form-control[readonly]:focus {
            background-color: #fff;
        }

        .btn-lg {
            transition: all .3s cubic-bezier(0.175, 0.985, 0.32, 1.375) !important;
            transform: scale(.994);
            border-radius: 15px;
            box-shadow: 0 5px 15px -8px blue;
        }

        .btn-lg:hover {
            transform: scale(1.02);
        }

        .file-load {
            top: 0px;
            right: 0px;
        }

        .footer {
            background-color: #f1f2f3;
        }
    </style>
</head>

<body class="d-flex flex-column h-100">
    <main>
        <div class="container">
            <h2 class="mb-3">学员签到检查程序&emsp;<button class="btn btn-sm btn-success btn-new">＋ 新开页面&nbsp;</button></h2>
            <div class="row">
                <div class="col-12">
                    <div class="form-group">
                        <label for="boxueguUrl">博学谷直播网址（直接复制助教端浏览器完整 URL）</label>
                        <p>
                            使用 <kbd><kbd>Ctrl</kbd> + <kbd>C</kbd></kbd> 和 <kbd><kbd>Ctrl</kbd> + <kbd>V</kbd></kbd> 来 <b>复制</b> / <b>粘贴</b> 更方便哦！！
                        </p>
                        <input type="text" class="form-control" id="boxueguUrl" placeholder="格式：https://view.csslcloud.net/api/view/assistant?roomid=房间ID&userid=讲师ID" />
                    </div>
                    <!-- <div class="form-group">
                        <label for="className">班级名称</label>
                        <input type="text" class="form-control" id="className">
                    </div> -->
                </div>
                <div class="col-md-6">
                    <div class="form-group position-relative">
                        <label for="studentList">完整学员列表 <small class="d-md-none d-lg-inline">可前缀，如：成都-XX</small></label>
                        <textarea class="form-control" id="studentList" rows="20" placeholder="例如：成都-张三,成都-李四..（支持普通换行，中英文逗号、分号、顿号）"></textarea>
                        <div class="position-absolute file-load">
                            <button class="btn btn-sm btn-outline-primary btn-load">导入</button>
                            <button class="btn btn-sm btn-outline-secondary btn-clean">解乱码</button>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="form-group">
                        <label for="onlineStudentList">在线学员列表</label>
                        <textarea class="form-control" id="onlineStudentList" rows="20" readonly placeholder="不需要填写，可能包含老师"></textarea>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="form-group">
                        <label for="offlineStudentList">未到学员列表</label>
                        <textarea class="form-control" id="offlineStudentList" rows="20" readonly placeholder="不需要填写，可能包含老师"></textarea>
                    </div>
                </div>
                <div class="col-12">
                    <button type="button" class="btn btn-primary btn-lg btn-block getOffline">立即获取学员在线状态</button>
                </div>
            </div>
            <div class="row mt-3 counter" style="display: none;">
                <div class="col-6">
                    <h2 class="text-success">在线人数：<span class="online-count"></span></h2>
                </div>
                <div class="col-6">
                    <h2 class="text-danger">离线人数：<span class="offline-count"></span></h2>
                </div>
            </div>
        </div>
    </main>


    <script>
        function queryString(params) {
            return '?' + Object.keys(params).map(key => `${ key }=${ params[key] }`).join('&');
        }

        function convertUrl(url) {
            const result = {};
            try {
                url.split('?')[1].split('&').forEach((i, { }, { }, kv = i.split('=')) => result[kv[0]] = kv[1]);
            } catch (error) {
                alert('博学谷直播地址填写有误请重新输入！')
                urlText.value = '';
            }
            return result;
        }

        function loadFile(el, file, encoding = 'gb2312') {
            const fr = new FileReader();
            fr.addEventListener('load', function(e) {
                console.log(this.result);
                el.value = this.result.trim();
            })
            fr.readAsText(file, encoding);
        }
    </script>
    <script>
        const fileInput = document.createElement('input');

        const urlText = document.querySelector('#boxueguUrl');
        const studentListText = document.querySelector('#studentList');
        const onlineStudentListText = document.querySelector('#onlineStudentList');
        const offlineStudentListText = document.querySelector('#offlineStudentList');
        const counter = document.querySelector('.counter');
        const onlineTips = document.querySelector('.online-count');
        const offlineTips = document.querySelector('.offline-count');
        console.warn(decodeURIComponent(atob('JUU2JTg4JTkwJUU5JTgzJUJEJUU2JUEwJUExJUU1JThDJUJBLSVFOCU5MSVBMyVFNyU5MSU5RSVFNyVBNSVCQSUyMCVFOCU5MSU5Nw==')));

        document.querySelector('.btn-new').addEventListener('click', () => window.open(location.href));

        document.querySelector('.btn-load').addEventListener('click', () => {
            fileInput.value = '';
            const attrs = { id: 'file1', type: 'file', accept: '.txt' };
            Object.keys(attrs).forEach(i => fileInput.setAttribute(i, attrs[i]));

            fileInput.addEventListener('change', e => {
                const file = fileInput.files[0];
                if (!file) return;

                loadFile(studentListText, file);
            })

            fileInput.click();
        });

        document.querySelector('.btn-clean').addEventListener('click', () => {
            const file = fileInput.files[0];
            if (!file) return;

            loadFile(studentListText, file, 'utf8');
        });

        const getOffline = document.querySelector('.getOffline');
        getOffline.addEventListener('click', () => {
            try {
                const ids = convertUrl(urlText.value.trim());

                if (!(ids.roomid && ids.userid)) {
                    alert('博学谷直播地址填写有误请重新输入！')
                    urlText.value = '';
                    return;
                }

                fetch('https://view.csslcloud.net/api/inline/room/onlineusers' + queryString({
                    ...ids, type: 2, value: ''
                })).then(res => res.json()).then(({ onlineUsers }) => {
                    const studentList = studentListText.value.trim().split(/[,;\r\n，；、]/)

                    const onlineStudentList = onlineUsers.map(i => i.name);
                    // const offlineStudentList = studentList.filter(i => !onlineStudentList.includes(i.trim()));
                    const offlineStudentList = studentList.filter(i => !onlineStudentList.some(j => j.endsWith(i.trim())));

                    onlineTips.innerText = onlineStudentList.length;
                    offlineTips.innerText = offlineStudentList.length;

                    onlineStudentList.length ? counter.removeAttribute('style') : counter.style = 'display: none;'

                    onlineStudentListText.value = onlineStudentList.join('\n');
                    offlineStudentListText.value = offlineStudentList.join('\n');
                });
            } catch (error) {
                alert('网络出错！')
            }
        })
    </script>
</body>

</html>
